home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Resources / Chat & Communication / Digsby build 37 / digsby_setup.exe / lib / mail / imapcheck.pyo (.txt) < prev    next >
Python Compiled Bytecode  |  2008-10-13  |  6KB  |  212 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.5)
  3.  
  4. import imaplib
  5. import time
  6. import re
  7. import email
  8. from datetime import datetime
  9. from pprint import pformat
  10. from mail.emailobj import DecodedEmail
  11. from mail import Email, AuthenticationError
  12. from logging import getLogger
  13. log = getLogger('imapcheck')
  14. from util import autoassign, callsback
  15. import traceback
  16.  
  17. class IMAPCheck(object):
  18.     
  19.     def __init__(self, maxfetch = 25):
  20.         self.maxfetch = maxfetch
  21.         self.cache = { }
  22.         self.srv = None
  23.  
  24.     
  25.     def login(self, host, port, ssl, user, password):
  26.         autoassign(self, locals())
  27.  
  28.     
  29.     def update(self):
  30.         if self.srv is not None:
  31.             self.srv.logout()
  32.             self.srv = None
  33.         
  34.         cls = None(getattr, imaplib if self.ssl else 'IMAP4')
  35.         srv = cls(self.host, self.port)
  36.         
  37.         try:
  38.             srv.login(srv._checkquote(self.user.encode('ascii')), self.password)
  39.         except (imaplib.IMAP4.error, imaplib.IMAP4_SSL.error):
  40.             raise AuthenticationError
  41.  
  42.         srv.select()
  43.         (res, lst) = srv.uid('search', None, '(UNSEEN UNDELETED)')
  44.         if res != 'OK':
  45.             raise Exception('could not retrieve unseen messages from the server')
  46.         
  47.         uids = None if lst[0] else []
  48.         log.info('%d unseen uids: %r', len(uids), uids)
  49.         msg_sendtimes = { }
  50.         unread_msgs = []
  51.         if uids:
  52.             (res, lst) = srv.uid('FETCH', ','.join(uids), '(INTERNALDATE FLAGS)')
  53.             if res != 'OK':
  54.                 raise Exception('could not retrieve message dates from the server')
  55.             
  56.             for resp in lst:
  57.                 
  58.                 try:
  59.                     dt = getDatetime(resp)
  60.                     uid = getUid(resp)
  61.                     flags = getFlags(resp)
  62.                     log.info('%s %r', uid, flags)
  63.                     if dt is not None and uid is not None and '\\Seen' not in flags and '\\Deleted' not in flags:
  64.                         unread_msgs.append((dt, uid))
  65.                         msg_sendtimes[uid] = dt
  66.                 continue
  67.                 except Exception:
  68.                     traceback.print_exc()
  69.                     continue
  70.                 
  71.  
  72.             
  73.         
  74.         count = len(unread_msgs)
  75.         unread_msgs.sort(reverse = True)
  76.         uids_to_fetch = []
  77.         uids_already_fetched = []
  78.         for dt, uid in unread_msgs[:self.maxfetch]:
  79.             
  80.             try:
  81.                 if uid not in self.cache:
  82.                     uids_to_fetch += [
  83.                         uid]
  84.                 else:
  85.                     uids_already_fetched += [
  86.                         uid]
  87.             continue
  88.             except Exception:
  89.                 traceback.print_exc()
  90.                 continue
  91.             
  92.  
  93.         
  94.         emailobjs = []
  95.         pref = pref
  96.         import common
  97.         if uids_to_fetch:
  98.             (res, lst) = srv.uid('fetch', ','.join(uids_to_fetch), '(BODY.PEEK[]<0.%d>)' % pref('imaplib.max_fetch_bytes', default = 5120, type = int))
  99.             if res != 'OK':
  100.                 raise Exception('could not retrieve message contents from the server')
  101.             
  102.             lst2 = []
  103.             currinfo = []
  104.             currdata = None
  105.             for resp in lst + [
  106.                 (None, None)]:
  107.                 if isinstance(resp, tuple):
  108.                     if currdata:
  109.                         lst2.append((currinfo, currdata))
  110.                         currdata = None
  111.                         currinfo = []
  112.                     
  113.                     currinfo.append(resp[0])
  114.                     currdata = resp[1]
  115.                     continue
  116.                 currinfo.append(resp)
  117.             
  118.             for resp in lst2:
  119.                 
  120.                 try:
  121.                     if isinstance(resp, tuple):
  122.                         (nfo, msg) = resp
  123.                         uid = getUid(nfo)
  124.                         sndtime = msg_sendtimes[uid]
  125.                         emailobj = emailFromString(uid, msg, sndtime)
  126.                         self.cache[uid] = emailobj
  127.                         emailobjs += [
  128.                             emailobj]
  129.                 continue
  130.                 except Exception:
  131.                     traceback.print_exc()
  132.                     continue
  133.                 
  134.  
  135.             
  136.         
  137.         for uid in uids_already_fetched:
  138.             emailobjs += [
  139.                 self.cache[uid]]
  140.         
  141.         log.info('untagged responses')
  142.         log.info(pformat(srv.untagged_responses))
  143.         srv.untagged_responses.clear()
  144.         self.srv = srv
  145.         return (count, emailobjs)
  146.  
  147.     
  148.     def markAsRead(self, msg, callback = None):
  149.         
  150.         try:
  151.             self.srv.uid('STORE', msg.id, '+FLAGS.SILENT', '(\\SEEN)')
  152.         except:
  153.             import traceback
  154.             traceback.print_exc()
  155.             return callback.error()
  156.  
  157.         callback.success()
  158.  
  159.     markAsRead = callsback(markAsRead)
  160.     
  161.     def delete(self, msg, callback = None):
  162.         
  163.         try:
  164.             self.srv.uid('STORE', msg.id, '+FLAGS.SILENT', '(\\DELETED \\SEEN)')
  165.         except:
  166.             import traceback
  167.             traceback.print_exc()
  168.             return callback.error()
  169.  
  170.         callback.success()
  171.  
  172.     delete = callsback(delete)
  173.  
  174.  
  175. def emailFromString(uid, s, sendtime_if_error):
  176.     return Email.fromEmailMessage(uid, DecodedEmail(email.message_from_string(s)), sendtime_if_error)
  177.  
  178.  
  179. def getDatetime(s):
  180.     timetuple = imaplib.Internaldate2tuple(s)
  181.     if timetuple is not None:
  182.         return datetime.fromtimestamp(time.mktime(timetuple))
  183.     
  184.  
  185. _uidMatcher = re.compile('UID ([0-9]+)\\D')
  186.  
  187. def getUid(s):
  188.     if isinstance(s, basestring):
  189.         vals = [
  190.             s]
  191.     else:
  192.         vals = s
  193.     for val in vals:
  194.         match = _uidMatcher.search(val)
  195.         if match:
  196.             return match.group(1)
  197.             continue
  198.     
  199.  
  200.  
  201. def getFlags(s):
  202.     return imaplib.ParseFlags(s)
  203.  
  204. if __name__ == '__main__':
  205.     i = IMAPCheck()
  206.     i.login('imap.aol.com', 143, False, 'digsby04', 'thisisnotapassword')
  207.     print 
  208.     print 'DONE'
  209.     print 
  210.     print repr(i.update())
  211.  
  212.